import React, { useEffect } from 'react'
import { Spin } from 'antd'
import styles from './Search.module.css'
import { FilterArea, ProductList } from '../../components'
import { useParams, useLocation } from 'react-router-dom'
import { getProductSearch } from '../../redux/ProductSearch/slice'
import { useAppDispatch, useSelector } from '../../redux/hook'
import { MainLayout } from '../../layout/MainLayout'

type MatchParmas = {
  keywords: string
}
export const Search: React.FC = () => {
  const { keywords } = useParams<MatchParmas>()
  const dispatch = useAppDispatch()
  const location = useLocation()
  console.log(location)
  const loading = useSelector((state) => state.productSearch.loading)
  const error = useSelector((state) => state.productSearch.error)
  const pagination = useSelector((state) => state.productSearch.pagination)
  const productList = useSelector((state) => state.productSearch.data)
  useEffect(() => {
    if (keywords) {
      dispatch(
        getProductSearch({
          nextPage: 1,
          pageSize: 10,
          keywords
        })
      )
    }
  }, [keywords, dispatch])
  const onPageChange = (nextPage, pageSize) => {
    if (keywords) {
      dispatch(
        getProductSearch({
          nextPage,
          pageSize,
          keywords
        })
      )
    }
  }
  if (loading) {
    return (
      <Spin
        size="large"
        style={{
          marginTop: 200,
          marginBottom: 200,
          marginLeft: 'auto',
          marginRight: 'auto',
          width: '100%'
        }}
      ></Spin>
    )
  }
  if (error) {
    return <div>网站出错：{error}</div>
  }
  return (
    <MainLayout>
      <div className={styles['product-list-container']}>
        <FilterArea />
      </div>
      <div className={styles['product-list-container']}>
        <ProductList
          data={productList}
          paging={pagination}
          onPageChange={onPageChange}
        />
      </div>
    </MainLayout>
  )
}
